package com.alex.common.tools;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;

/**
 * MD5的全称是 Message-Digest Algorithm 5
 * <p>
 * 在90年代初由MIT的计算机科学实验室和RSA Data Security Inc发明，经MD2、MD3和MD4发展而来。<br>
 * MD5将任意长度的"字节串"变换成一个128bit的大整数，并且它是一个不可逆的字符串变换算法<br>
 * 即该加密算法是单向加密，加密的数据不能再通过解密还原。
 * 
 * @author <a href="mailto:huqiyes@gmail.com">huqi</a>
 * @serialData 2007
 */
public final class MD5Utils {

	private static final String MD5_ALGORITHM = "MD5";

	private MD5Utils() {
	}

	private static MessageDigest getMD5DigestAlgorithm()
			throws NoSuchAlgorithmException {
		return MessageDigest.getInstance(MD5_ALGORITHM);
	}

	public static byte[] getMD5Digest(byte source[])
			throws NoSuchAlgorithmException {
		return getMD5DigestAlgorithm().digest(source);
	}

	public static byte[] getMD5Digest(String source)
			throws NoSuchAlgorithmException {
		return getMD5Digest(source.getBytes());
	}

	public static String getMD5DigestHex(byte source[])
			throws NoSuchAlgorithmException {
		return new String(Hex.encodeHex(getMD5Digest(source)));
	}

	public static String getMD5DigestHex(String source) {
		try {
			return new String(Hex.encodeHex(getMD5Digest(source)));
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException(e);
		}
	}

	public static String getMD5DigestBase64(byte source[])
			throws NoSuchAlgorithmException {
		return new String(Base64.encodeBase64(getMD5Digest(source)));
	}

	public static String getMD5DigestBase64(String source)
			throws NoSuchAlgorithmException {
		return new String(Base64.encodeBase64(getMD5Digest(source)));
	}

	public static void main(String[] args) throws NoSuchAlgorithmException {
	}
}
